<?php

require('configs/include.php');

class c_finalizar_kernel extends super_controller {

    public function finalizar() {
        $kernel = new kernel($this->post);
        if (is_empty($kernel->get('id'))) {
            throw_exception("Debe seleccionar un kernel");
        } else {
            if ($this->comprimir($kernel)) {
                $this->orm->connect();
                $this->orm->update_data("by_id", $kernel);
                $this->orm->close();
                $this->type_warning = "success";
                $this->msg_warning = "Operación exitosa";
                $this->img_warning = "correct.png";
                $this->engine->assign('img_warning', $this->img_warning);
                $this->temp_aux = 'message.tpl';
                $this->engine->assign('type_warning', $this->type_warning);
                $this->engine->assign('msg_warning', $this->msg_warning);
            }
        }
    }

    public function comprimir($kernel) {

        $cod['kernel']['id'] = $kernel->get('id');
        $options['kernel']['lvl2'] = "by_one";
        $options['modulo']['lvl2'] = "all";
        $options['programa']['lvl2'] = "all";

        $components['kernel']['modulo'] = array("k_m");
        $components['modulo']['programa'] = array("m_p");

        $this->orm->connect();
        $this->orm->read_data(array("kernel", "modulo", "programa"), $options, $cod);
        $kernels = $this->orm->get_objects("kernel", $components);
        $this->orm->close();

        //Generar los archivos de codigo fuente del kernel.
        $x = TRUE;
        foreach ($kernels as $kernel1) {
            $version = $kernel1->get('version');
            $rutak = $version;
            if (!file_exists($rutak)) {
                mkdir($rutak, 0777, true);
                if (count($kernel1->components['k_m']) > 0) {
                    foreach ($kernel1->components['k_m'] as $modulo) {
                        $rutam = $rutak . "/" . $modulo->get('nombre');
                        if (!file_exists($rutam)) {
                            mkdir($rutam, 0777, true);
                            if (count($modulo->components['m_p']) > 0) {
                                foreach ($modulo->components['m_p'] as $programa) {
                                    if (count($programa) > 0) {
                                        $rutap = $rutam . "/" . $programa->get('nombre') . ".php";
                                        if (!file_exists($rutap)) {
                                            $fl = fopen($rutap, "a") or die("Error al cargar el programa.");
                                            fwrite($fl, "/*" . "\r\n" . $programa->get('nombre') . ".php" . "\r\n\r\n" . $programa->get('funcionalidad') . "\r\n" . "*/");
                                            fwrite($fl, "\r\n\r\n" . $programa->get('codigo_fuente'));
                                            fclose($fl);
                                        }
                                    }
                                }
                            } else {
                                $x = FALSE;
                            }
                        }
                    }
                }  else {
                    $x = FALSE;
                }
            }
        }

        //Comprimir el kernel
        $zip = new ZipArchive();
        $dir = $kernels[0]->get('version') . "/";
        $rutaFinal = "recursos/kernel/";
        $filename = $kernels[0]->get('version') . '.zip';

        if ($zip->open($filename, ZIPARCHIVE::CREATE) === true) {
            $this->agregar_zip($dir, $zip);
            $zip->close();
            @rename($filename, "$rutaFinal$filename");
        }

        $this->rrmdir($dir);
        return $x;
    }

    // Fuente: http://garabatoslinux.net/comprimir-un-directorio-completo-en-zip-desde-php.html
    public function agregar_zip($dir, $zip) {
        if (is_dir($dir)) {
            if ($da = opendir($dir)) {
                while (($archivo = readdir($da)) !== false) {
                    if (is_dir($dir . $archivo) && $archivo != "." && $archivo != "..") {
                        $this->agregar_zip($dir . $archivo . "/", $zip);
                    } elseif (is_file($dir . $archivo) && $archivo != "." && $archivo != "..") {
                        $zip->addFile($dir . $archivo, $dir . $archivo);
                    }
                }
                closedir($da);
            }
        }
    }

    // Fuente: http://php.net/manual/es/function.rmdir.php
    function rrmdir($dir) {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir . "/" . $object) == "dir")
                        $this->rrmdir($dir . "/" . $object);
                    else
                        unlink($dir . "/" . $object);
                }
            }
            reset($objects);
            rmdir($dir);
        }
    }

    public function display() {
        $options['kernel']['lvl2'] = "by_state";
        $this->orm->connect();
        $this->orm->read_data(array("kernel"), $options);
        $kernels = $this->orm->get_objects("kernel");
        $this->orm->close();
        // Verificando que existan kernel con estado iniciado
        if (count(kernels) == 0) {
            throw_exception("No hay kernels para finalizar");
        }
        $this->engine->assign('kernels', $kernels);
        $varAux = $this->gvar['n_index'] . " -> " . $this->gvar['n_request'];
        $this->engine->assign('ubicationPath', $varAux);
        $this->engine->display('header.tpl');
        $this->engine->display($this->temp_aux);
        $this->engine->display('finalizar_kernel.tpl');
        $this->engine->display('footer.tpl');
    }

    public function run() {
        if ($_SESSION['usuario']['tipo'] == "lider") {
            try {
                if (isset($this->get->option)) {
                    $this->{$this->get->option}();
                }
            } catch (Exception $e) {
                $this->error = 1;
                $this->msg_warning = $e->getMessage();
                $this->img_warning = "incorrect.png";
                $this->engine->assign('type_warning', $this->type_warning);
                $this->engine->assign('msg_warning', $this->msg_warning);
                $this->engine->assign('img_warning', $this->img_warning);
                $this->temp_aux = 'message.tpl';
            }
            $this->display();
        } else {
            $this->engine->display('header.tpl');
            $this->engine->display('sinPermisos.tpl');
            $this->engine->display('footer.tpl');
        }
    }

}

$call = new c_finalizar_kernel();
$call->run();
?>
